package com.zhku.meeting.util;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Iterator;
import java.util.Set;

/**
 * 参数校验工具类
 * @param <T>
 */
public class ValidateUtil<T> {

	private static Validator validator = Validation.buildDefaultValidatorFactory().getValidator();

	/**
	 * 验证参数
	 */
	public void isValid(T t) {
		if (null == t) {
			return;
		}
		// 验证某一个对象
		StringBuffer buffer = new StringBuffer();// 用于存储验证后的错误信息
		Set<ConstraintViolation<Object>> constraintViolationList = validator.validate(t);// 验证某个对象,，其实也可以只验证其中的某一个属性的
		if(CollectionUtil.isEmpty(constraintViolationList)) {
			return;
		}
		for(ConstraintViolation<Object> constraintViolation : constraintViolationList) {
			String propertyKey = constraintViolation.getPropertyPath().toString();
			String message = constraintViolation.getMessage();
			buffer.append("["+propertyKey+"]").append(message);

			throw new IllegalArgumentException(buffer.toString());
		}
	}

	public JSONObject getVaildMessage(T t){
		if (null == t) {
			return null;
		}
		// 验证某一个对象
		JSONObject result = new JSONObject();
		Set<ConstraintViolation<Object>> constraintViolationList = validator.validate(t);// 验证某个对象,，其实也可以只验证其中的某一个属性的
		if(CollectionUtil.isEmpty(constraintViolationList)) {
			return null;
		}
		for(ConstraintViolation<Object> constraintViolation : constraintViolationList) {
			String propertyKey = constraintViolation.getPropertyPath().toString();
			String message = constraintViolation.getMessage();
			result.put(propertyKey,message);
		}
		return result;
	}
}
